package com.yb.xczx.cloud.auth.handler;

import com.yb.core.enums.HttpCode;
import com.yb.core.model.XczxResult;
import com.yb.xczx.cloud.auth.bean.LoginSuccessResult;
import com.yb.xczx.cloud.auth.bean.XczxAbstractAuthenticationToken;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/19 12:30
 * FileName: LoginSuccessHandler
 * Description:
 */
public class LoginFailedHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            String msg="";
        XczxResult xczxResult=null;

            if(exception instanceof UsernameNotFoundException){

                xczxResult=XczxResult.error(HttpCode.Response.USER_NOT_FOUND);
            }

            if(exception instanceof BadCredentialsException){

                xczxResult=XczxResult.error(HttpCode.Response.PASSWORD_ERROR.getCode(),exception.getMessage());
            }
            if(exception instanceof InsufficientAuthenticationException){

                xczxResult=XczxResult.error(HttpCode.Response.UNAUTHORIZED);

            }
            response.getWriter().write(xczxResult.toJSON());

    }
}
